package com.haierCamera.customapplication.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.vo.GetDeviceEntity;
import com.haierCamera.customapplication.databinding.HzklActivityDeviceSearchBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.custom.BaseListenerOnClik;
import com.haierCamera.customapplication.ui.mediaplay.MediaPlayActivity;
import com.haierCamera.customapplication.ui.search.cn.CNPinyin;
import com.haierCamera.customapplication.ui.search.cn.CNPinyinFactory;
import com.haierCamera.customapplication.ui.search.cn.CNPinyinIndex;
import com.haierCamera.customapplication.ui.search.cn.CNPinyinIndexFactory;
import com.haierCamera.customapplication.ui.search.search.TextViewChangedOnSubscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class HZKLDeviceSearchActivity extends BaseActivity {

    HzklActivityDeviceSearchBinding binding;
    List<GetDeviceEntity> mList = new ArrayList<>();
    HZKLDeviceList2Adapter adapter;

    List<CNPinyin<GetDeviceEntity>> list_CN = new ArrayList<>();
    private Subscription subscription;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_device_search);
        binding.tvCancel.setOnClickListener((v)->{
            finish();
        });


        /**
         * 下面是检索回调
         */
        TextViewChangedOnSubscribe plateSubscribe = new TextViewChangedOnSubscribe();
        plateSubscribe.addTextViewWatcher(binding.edSearch);
        subscription = Observable.create(plateSubscribe).debounce(100, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .switchMap(new Func1<String, Observable<ArrayList<CNPinyinIndex<GetDeviceEntity>>>>() {
                    @Override
                    public Observable<ArrayList<CNPinyinIndex<GetDeviceEntity>>> call(final String s) {

                        return createObservable(s).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
                    }
                }).subscribe(new Subscriber<ArrayList<CNPinyinIndex<GetDeviceEntity>>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(ArrayList<CNPinyinIndex<GetDeviceEntity>> cnPinyinIndices) {
                        adapter.upDate(cnPinyinIndices);
//                        if (cnPinyinIndices.size()!=0) {
//                            binding.rcv.setVisibility(View.VISIBLE);
//                            binding.ivEmpty.setVisibility(View.GONE);
//                        }
                    }
                });

        binding.rcv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HZKLDeviceList2Adapter(this);
        binding.rcv.setAdapter(adapter);
        binding.rcv.setVisibility(View.VISIBLE);
        binding.ivEmpty.setVisibility(View.GONE);
        adapter.setOnItemOnClick(new BaseListenerOnClik() {
            @Override
            public void onClick(int position) {
                getDeviceChannel(adapter.getData().get(position).cnPinyin.data.serialNumber,position);
            }
        });
        initData();

    }

    private void initData(){
        mList = Business.getInstance().getmDeviceList();
        getPinyinList();
    }

    private void getPinyinList() {
        subscription = Observable.create(new Observable.OnSubscribe<List<CNPinyin<GetDeviceEntity>>>() {
            @Override
            public void call(Subscriber<? super List<CNPinyin<GetDeviceEntity>>> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    List<CNPinyin<GetDeviceEntity>> contactList = CNPinyinFactory.createCNPinyinList(mList);
                    Log.i("TAG","list-size-" + contactList.size());
                    Collections.sort(contactList);
                    subscriber.onNext(contactList);
                    subscriber.onCompleted();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<CNPinyin<GetDeviceEntity>>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CNPinyin<GetDeviceEntity>> cnPinyins) {
                        list_CN.addAll(cnPinyins);
                        adapter.notifyDataSetChanged();
                        Log.i("TAG","cnPinyins-size-" + cnPinyins.size());
                    }
                });
    }

    private void getDeviceChannel(String sn ,int i){
        showLoadingDialog();
        Business.getInstance().getDeviceInfo2(sn,new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    Log.i("TAG","size-" + ((Bundle) msg.obj).getIntegerArrayList("list").size());

                    for (int j = 0; j < ((Bundle) msg.obj).getIntegerArrayList("list").size(); j++) {
                        Log.i("TAG","getDeviceChannel-" + ((Bundle) msg.obj).getIntegerArrayList("list").get(j));
                    }
                    dismissLoadingDialog();
                    startActivity(new Intent(HZKLDeviceSearchActivity.this, MediaPlayActivity.class)
                            .putExtra("TYPE", 1)
                            .putExtra("RESID", "0")
                            .putExtra("RESDEVICEID", adapter.getData().get(i).cnPinyin.data.serialNumber)
                            .putExtra("RESPWD", adapter.getData().get(i).cnPinyin.data.securityCode)
                            .putExtra("RESNAME", adapter.getData().get(i).cnPinyin.data.name)
                            .putExtra("RESACCOUNTDEVICEID", adapter.getData().get(i).cnPinyin.data.accountDeviceId)
                            .putExtra("RESPICTURE", adapter.getData().get(i).cnPinyin.data.picture)
                            .putExtra("RESCHANNELS", ((Bundle) msg.obj).getIntegerArrayList("list")));
                }

            }
        });
    }

    /**
     * 搜索订阅
     * @return
     */
    private Observable<ArrayList<CNPinyinIndex<GetDeviceEntity>>> createObservable(final String keywork) {
        return Observable.create(new Observable.OnSubscribe<ArrayList<CNPinyinIndex<GetDeviceEntity>>>() {
            @Override
            public void call(Subscriber<? super ArrayList<CNPinyinIndex<GetDeviceEntity>>> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext(CNPinyinIndexFactory.indexList(list_CN, keywork));
                }
            }
        });
    }

}
